/**
* 
* @Depends ruleMgr.js
*/
/** @lends ksg.bizrule.bizRules# */
ksg.bizrule.bizRules["getGoogleContacts"] = function(options, onSuccess, onError) {
	//This rule cannot work if the google contacts service has not been setup, and if the user has not
	//authenticated against system system.  Although there are suposedly public contacts we can work with read 
	//only, these rules are currently only setup to work with the authenticated user's contacts.
	if(ksg.google.contactsService && ksg.google.loginToken) {
		var query = new google.gdata.contacts.ContactQuery(options.baseContactFeed);
		query.setMaxResults(options.maxContactResults);
		
		//This is the call to Google to get the list of contacts.
		//TODO this call could also take filter/sort criteria.  Once the core filter/sort mechanism
		//is setup for base.bizproc we should support it here.
		ksg.google.contactsService.getContactFeed(query,
			function(results) {
				//TODO this code creates a simple array for bizobjs but should be using ksg.App.bizObjMgr.createList(),
				//but that is not ready yet.
				var bizObjs = [], entries = results.feed.entry;
				for(var i in entries) {
					var entry = entries[i];
					var bizObj = ksg.App.bizObjMgr.create("GContact");
					bizObj._gContact = entry;
					bizObj.id = entry.getId().getValue();
					
					//Contact name
					var name = entry.getName();
					if(name) {
						if(name.getGivenName())
							bizObj.firstName = name.getGivenName().getValue();
						if(name.getFamilyName())
						bizObj.lastName = name.getFamilyName().getValue();
					}
					
					//Contact email
					var emailAddresses = entry.getEmailAddresses();
					if(emailAddresses && emailAddresses.length > 0)
						bizObj.email = emailAddresses[0].getAddress();

					//Contact avatar
					//TODO Figure out how the hell to get a valid href for the avatar photo set for the contact.
					//the href returned by the getContactPhotoLink() is actually not usable and needs to be setup with
					//the authentication token, but I am unaware of how to do that properly.  It is not just
					//adding ?token=options.loginToken.  For now, the avatar photo is broken link.
					bizObj.avatarUrl = entry.getContactPhotoLink().getHref();
					var q2 = new google.gdata.client.Query(bizObj.avatarUrl);
					var xx = ksg.google.contactsService.getFeed(q2, function(results) {
						var x = results;
					},
					function(error) {
						var y =error;
					});
					//------------
					
					//Contact phone
					var phones = entry.getPhoneNumbers();
					if(phones && phones.length > 0)
						bizObj.phone = phones[0].getValue();
					
					//Contact notes
					var jots = entry.getJots();
					if(jots && jots.length > 0)
						bizObj.jot = jots[0].getValue();
					
					//Contact addresses
					//TODO populate address list as bizobj list
										
					bizObjs.push(bizObj);
				}
				var rc = {
					response:{bizObjs:bizObjs}
				};
				onSuccess(rc);
			},
			function(error) {
				onError(error);
			});
	}
};


ksg.bizrule.bizRules["updateGoogleContact"] = function(contact, onSuccess, onError) {
	
	if(contact && contact._gContact) {
		var gCon = contact._gContact;
		var name = gCon.getName();
		if(name == null) {
			name = new google.gdata.Name();
			gCon.setName(name);
		}
		
		var setField = function(parentName, fieldName, val) {
			var parent = gCon["get"+parentName].call(gCon);
			if(parent["get"+fieldName]() == null)
				parent["set"+fieldName](new google.gdata[fieldName]());
			if(val == null)
				parent["set"+fieldName](null);
			else
				parent["get"+fieldName]().setValue(val);
		};
		var setFirstItemField = function(parentName, itemType, fieldName, val, itemType2) {
			if(itemType2 == null)
				itemType2 = itemType;
			var items = gCon["get"+parentName]();
			var hasItem = (items != null && items.length > 0);
			var item = hasItem?items[0]:new (ksg.bizobj.BizObj.getValue(google.gdata, itemType2))();
			item["set"+fieldName](val);	
			if(!hasItem)
				gCon["add"+itemType](item);
			return hasItem;
		};
		
		setField("Name", "GivenName", contact.firstName==""?null:contact.firstName);
		setField("Name", "FamilyName", contact.lastName==""?null:contact.lastName);
		setField("Name", "FullName", null);
		setFirstItemField("EmailAddresses", "EmailAddress", "Address", contact.email, "Email");
		setFirstItemField("EmailAddresses", "EmailAddress", "Rel", "http://schemas.google.com/g/2005#other", "Email");
		if(!setFirstItemField("PhoneNumbers", "PhoneNumber", "Value", contact.phone))
			setFirstItemField("PhoneNumbers", "PhoneNumber", "Label", "Phone");
		if(!setFirstItemField("Jots", "Jot", "Value", contact.jot, "contacts.Jot"))
			setFirstItemField("Jots", "Jot", "Rel", google.gdata.contacts.Jot.REL_OTHER);

		//This is the actual call to Google to update the contact.
		gCon.updateEntry(function(entryRoot) {
			var entry = entryRoot.entry;
			contact._gContact = entry;
			onSuccess(contact);
		},
		function(error) {
			//TODO this is not properly sending back the error as expected in the base bizproc.
			onError(error);
		});
	}	
};


ksg.bizrule.bizRules["deleteGoogleContact"] = function(contact, onSuccess, onError) {
	if(contact && contact._gContact) {
		var gCon = contact._gContact;
		gCon.deleteEntry(function() {
			onSuccess({});
		},
		function(error) {
			onError(error);
		});
	}
};

